package com.liebaut.util;

import org.hibernate.cfg.Environment;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.Oracle10gDialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

public class SchemaExporter {

    public static void main(String[] args) {
        SchemaExporter exporter = new SchemaExporter();
        exporter.export("mysql", MySQLDialect.class);
        exporter.export("sqlserver", SQLServerDialect.class);
        exporter.export("oracle", Oracle10gDialect.class);
    }

    LocalContainerEntityManagerFactoryBean entityManagerFactory;

    public SchemaExporter() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/test-context.xml");
        entityManagerFactory = applicationContext.getBean(LocalContainerEntityManagerFactoryBean.class);
    }

    public void export(String name, Class dialect) {
        org.hibernate.ejb.Ejb3Configuration cfg = new org.hibernate.ejb.Ejb3Configuration();
        org.hibernate.ejb.Ejb3Configuration configured = cfg.configure(
                entityManagerFactory.getPersistenceUnitInfo(),
                entityManagerFactory.getJpaPropertyMap());
        configured.setProperty(Environment.DIALECT, dialect.getName());

        SchemaExport schemaExport = new SchemaExport(configured.getHibernateConfiguration());
        schemaExport.setDelimiter(";");
        schemaExport.setOutputFile(name + ".sql");
        schemaExport.create(false, false);
    }

}
